// pages/createRoom/createRoom.js
const app = getApp()

Page({
  data: {
    radioArray: [
      {id: 0, title: "5人", checked: false},
      {id: 1, title: "6人", checked: false},
      {id: 2, title: "7人", checked: false},
      {id: 3, title: "8人", checked: false},
    ],
    currentNumber: 4,
    abettorNum: 0,
    detectiveNum: 2,
  },

  radioChange: function(res) {
    var arrs = this.data.radioArray
    var value = res.detail.value
    for (const item in arrs) {
      arrs[item].checked = (arrs[item].title == value)
    }
    if (value == arrs[0].title) {
      this.setData({
        radioArray: arrs,
        currentNumber: 5,
        abettorNum: 0,
        detectiveNum: 3
      })
    } else if (value == arrs[1].title) {
      this.setData({
        radioArray: arrs,
        currentNumber: 6,
        abettorNum: 1,
        detectiveNum: 3
      })
    } else if (value == arrs[2].title) {
      this.setData({
        radioArray: arrs,
        currentNumber: 7,
        abettorNum: 1,
        detectiveNum: 4
      })
    } else {
      this.setData({
        radioArray: arrs,
        currentNumber: 8,
        abettorNum: 1,
        detectiveNum: 5
      })
    }
  },

  onMinusTap: function() {
    this.setData({
      currentNumber: this.data.currentNumber - 1
    })
  },

  onPlusTap: function() {
    this.setData({
      currentNumber: this.data.currentNumber + 1
    })
  },

  createRoom: async function() {
    var that = this
    wx.showLoading({
      title: '创建中...',
    })
    const db = wx.cloud.database();
    const roomArr = await db.collection("room").get()
    const room = roomArr.data.length + 10000
    console.log('[云数据库] [user] 查询: ', roomArr.data.length)
    db.collection("room").add({
      data: {
        _id: room.toString(),
        owner: app.globalData.openid,
        totalNum: this.data.currentNumber,
        abettorNum: this.data.abettorNum,
        detectiveNum: this.data.detectiveNum
      },
      success: function(res) {
        console.log('[云数据库] [room] 插入: ', res)
        that.changeUserStatus(room)
      },
      fail: function(res) {
        console.log('[云数据库] [room] 插入失败: ', res)
        wx.hideLoading()
        wx.showToast({
          title: '创建房间失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  changeUserStatus: async function(room) {
    wx.cloud.callFunction({
      name: "modifyUser",
      data: {
        status: "ready",
        room: room.toString(),
        solve: false,
      },
      success: function (res) {
        console.log('[云数据库] [user] 更新: ', res)
        wx.hideLoading()
        wx.reLaunch({
          url: '../startGame/startGame?room=' + room.toString()
        })
      },
      fail: function (res) {
        console.log('[云数据库] [user] 更新失败: ', res)
        wx.hideLoading()
        wx.showToast({
          title: '创建房间失败，请重试',
          icon: 'none',
        })
      }
    })
  }
})